package com.xiaoc.bulldozer.controller;

import com.xiaoc.bulldozer.common.ResponseCode;
import com.xiaoc.bulldozer.common.dto.CommonConfigDto;
import com.xiaoc.bulldozer.common.dto.CommonConfigQueryDto;
import com.xiaoc.bulldozer.common.model.CommonConfig;
import com.xiaoc.bulldozer.common.service.CommonConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/sys/config")
public class SysConfigController extends AdminBaseController {

    @Resource(name = "commonConfigService")
    private CommonConfigService commonConfigService;

    /**
     * 查询列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ModelAndView list(CommonConfigQueryDto queryDto) {

        List<CommonConfig> allCommonConfigList = commonConfigService.getAllCommonConfigList();

        Map<String, Object> params = new HashMap<String, Object>();

        params.put("commonConfigList", allCommonConfigList);

        return renderHtml("sys/list.html", params);
    }

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public ModelAndView edit(String configKey) {
        CommonConfig commonConfig = commonConfigService.getCommonConfigFromDb(configKey);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("commonConfig", commonConfig);
        return renderHtml("sys/edit.html", params);
    }

    @RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
    public ModelAndView save(@RequestBody CommonConfigDto commonConfigDto) {

        if (StringUtils.isEmpty(commonConfigDto.getConfigKey())) {
            return jsonFailed(ResponseCode.BUSINESS_ERROR.getCode(), "key不能为空");
        }

        if (StringUtils.isEmpty(commonConfigDto.getConfigValue())) {
            return jsonFailed(ResponseCode.BUSINESS_ERROR.getCode(), "value不能为空");
        }

        commonConfigService.updateConfigValue(commonConfigDto.getConfigKey().trim(), commonConfigDto.getConfigValue().trim());

        return jsonSucess();
    }

}
